package fun.yyds.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;


@Slf4j
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Value("${thread.max}")
    private Integer maxThreads;

    @Value("${thread.core}")
    private Integer coreThreads;

    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        if (coreThreads == null || maxThreads == null) {
            int i = Runtime.getRuntime().availableProcessors();
            coreThreads = i * 2;
            maxThreads = (int) (coreThreads / (1 - 0.9));
        }

        log.info("核心线程数：" + coreThreads + " 最大线程数：" + maxThreads);
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(coreThreads);
        //最大线程数
        executor.setMaxPoolSize(maxThreads);
        //队列容量
        executor.setQueueCapacity(1024);
        //活跃时间
        executor.setKeepAliveSeconds(300);
        //线程名字前缀
        executor.setThreadNamePrefix("TaskExecutePool-");
        executor.setAllowCoreThreadTimeOut(false);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        return executor;

    }
}
